 //
//  WSNetworkTool.swift
//  微博
//
//  Created by 武莎莎 on 15/9/6.
//  Copyright © 2015年 itcast. All rights reserved.
//

import UIKit
import AFNetworking
import ReactiveCocoa

class WSNetworkTool: AFHTTPSessionManager {

    // 回调地址
    var redirecturi:String = "https://www.baidu.com"
    private var clientId:String = "2872343946"
    private var appSecret = "b5be20c19aae352479696ef419ac6a1f"
    
    static let sharedNetworkTool:WSNetworkTool = {
        let instance = WSNetworkTool(baseURL: nil)
        
        instance.responseSerializer.acceptableContentTypes!.insert("text/plain")
        
        return instance
    }()
    
    // 计算型属性：只读 末尾不需要加（）
    var oauthURL:NSURL{
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(clientId)&redirect_uri=\(redirecturi)"
        return NSURL(string: urlString)!
    }
    // 发送获取accessToken的网络请求
    func loadAccessToken(code:String) ->RACSignal{
        
        let urlString = "https://api.weibo.com/oauth2/access_token"
        print(code)
        let parameter = [
            "client_id":clientId,
            "client_secret":appSecret,
            "grant_type":"authorization_code",
            "code":code,
            "redirect_uri":redirecturi
        ]
        print(code)
        return request(.requestPost, urlString: urlString, paras: parameter, withToken: false)
    }
    
    // MARK:加载用户个人信息
    func loadUserInfo(uid:String) ->RACSignal {
        let urlString = "https://api.weibo.com/2/users/show.json"
        let parameters = ["uid":uid]
        return request(.requestGet, urlString: urlString, paras: parameters, withToken: true)
    }
    // MARK:加载微博数据
    // TODO: 用户微博的接口
    func loadStatus() -> RACSignal{
            let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
            return request(.requestGet, urlString: urlString, paras: nil)
    }
    //对AFN的Get和set请求进行了封装
    func request(methodName:requestMethod, urlString:String, var paras:[String:AnyObject]?, withToken:Bool = true)->RACSignal{
        
        return RACSignal .createSignal({(subscriber) -> RACDisposable! in
            
            if withToken {
                guard let token = WSUserAccountViewModel.sharedUserAccount.accessToken else {
                    subscriber.sendError(NSError(domain: "com.itwss.error", code: -1333, userInfo: ["tip":"用户token为空"]))
                    return nil
                }
        
                if paras == nil {
                    paras = [String:AnyObject]()
                }
                paras!["access_token"] = token
            }
            let successCallBack = {(task:NSURLSessionDataTask, result:AnyObject)->Void in 
                subscriber.sendNext(result)
                subscriber.sendCompleted()
            }
            let failCallBack = {(task:NSURLSessionDataTask, error:NSError)->Void in
                subscriber.sendError(error)
            }
            
            switch methodName{
            case .requestGet:
                self.GET(urlString, parameters: paras, success: successCallBack, failure: failCallBack)
            case .requestPost:
                self.POST(urlString, parameters: paras, success: successCallBack, failure: failCallBack)
            }
            return nil
        })
    }
    
}
